<template>
  <div>
    <div class="flex justify-content-between mb10">
      <div class="flex">
        <div>
          <span class="mr5"><a-button type="primary"  :loading="addLoading" @click="handleAdd"> <template
              #icon><PlusOutlined/> </template>添加培训项目</a-button></span>
          <span  v-if="(tableDataAll.length - filterDataAll.length) > 0">
            <a-checkbox v-model:checked="showChecked" @change="handleChangeBtn">{{showChecked?'显示有效':'显示无效'}}</a-checkbox>
            <span class="ml5">【有效{{filterDataAll.length}}条) / 无效({{tableDataAll.length - filterDataAll.length}}条】</span>
          </span>
        </div>
      </div>
    </div>
    <a-table
        :columns="columns"
        rowClassName="items"
        :loading="tableLoading"
        rowKey="id"
        :pagination="false"
        :data-source="tableData"
        size="small"  bordered>
      <template #bodyCell="{ column,text,record,index }">
        <template v-if="column.dataIndex === 'xiangMuDaiMa'">
          <div v-if="!record.id || record.edit">
            <a-select class="w100" placeholder="请选择" v-model:value="record.xiangMuDaiMa" @change="handleSearchInfo(record)">
              <a-select-option :value="item.xiangMuDaiMa" :key="item.id" v-for="item in chuanboZhengshuList">{{item.xiangMuDaiMa}}</a-select-option>
            </a-select>
          </div>
          <div v-else>{{record.xiangMuDaiMa}}</div>
        </template>
        <template v-if="column.dataIndex === 'xiangMuMing'">
          <div v-if="!record.id || record.edit"><a-input style="text-align: center" v-model:value="record.xiangMuMing" placeholder="请填写" maxlength="100"></a-input></div>
          <div v-else>{{record.xiangMuMing}}</div>
        </template>
        <template v-if="column.dataIndex === 'qianFaJiGuan'">
          <div v-if="!record.id || record.edit"><a-input style="text-align: center" v-model:value="record.qianFaJiGuan" placeholder="请填写" maxlength="100"></a-input></div>
          <div v-else>{{record.qianFaJiGuan}}</div>
        </template>
        <template v-if="column.dataIndex === 'qianFaRiQi'">
          <div v-if="!record.id || record.edit">
            <a-date-picker style="text-align: center" v-model:value="record.qianFaRiQi" @change="handleChangeQianFa(record)" class="w100"
                           format="YYYY-MM-DD" value-format="YYYY-MM-DD" placeholder="请填写" maxlength="100"></a-date-picker>
          </div>
          <div v-else>{{record.qianFaRiQi}}</div>
        </template>
        <template v-if="column.dataIndex === 'youXiaoQi'">
          <div v-if="!record.id || record.edit">
            <a-date-picker style="text-align: center" v-model:value="record.youXiaoQi" class="w100" format="YYYY-MM-DD" value-format="YYYY-MM-DD" placeholder="请填写" maxlength="100"></a-date-picker>
          </div>
          <div v-else>{{record.youXiaoQi}}</div>
        </template>
        <template v-if="column.dataIndex === 'zhuangTai'">
          <div v-if="!record.id || record.edit">
            <a-select placeholder="请选择" class="w100" style="text-align: center" v-model:value="record.zhuangTai">
              <a-select-option :value="1">有效</a-select-option>
              <a-select-option :value="0">无效</a-select-option>
            </a-select>
          </div>
          <div v-else>{{record.zhuangTai==1?"有效":"无效"}}</div>
        </template>
        <template v-if="column.dataIndex === 'operation'">
          <div class="editable-row-operations">
              <span class="mr5">
                <a-button  v-if="record.id && !record.edit"  type="primary"  class="mr10" @click="handleEdit(index,record.id)" size="small"> 编辑</a-button>
                <a-button  v-if="record.id && record.edit"  type="primary"  class="mr10" @click="handleEditSave(index,record.id)" size="small">保存</a-button>
                <a-button  v-if="record.id && record.edit"  type="primary"  class="mr10" @click="handleEditDel(index,record.id)" size="small">取消</a-button>
                <a-popconfirm v-if="record.id && !record.edit" title="你确定删除吗?" @confirm="handleDelete(record.id)">
                   <a-button type="primary" size="small" danger> <template #icon><CloseOutlined  style="font-size:12px"/></template>删除</a-button>
                </a-popconfirm>
                <a-button  v-if="!record.id"  type="primary"  class="mr10" @click="handleSave(index)" size="small"><template
                    #icon><PlusOutlined/></template>保存</a-button>
                <a-popconfirm  v-if="!record.id" title="你确定删除吗?" @confirm="handleDeleteItem(index)">
                   <a-button type="primary" size="small" danger> <template #icon><CloseOutlined  style="font-size:12px"/></template>删除</a-button>
                </a-popconfirm>
              </span>
          </div>
        </template>
      </template>
    </a-table>
  </div>
</template>
<script setup>
const showChecked = ref(false)
const cid = ref("")
const cname = ref("")
const addWorkRef = ref(null)
const addLoading = ref(false)
const tableLoading = ref(false)
const total = ref(0)
const tableData = ref([])
const tableDataAll= ref([])
const filterDataAll= ref([])
const chuanboZhengshuList = ref([])
const emits = defineEmits(["success"])
const queryParams = reactive({
  pageNo: 1,
  pageSize: 500,
  chuanYuanId:"",
})

const columns = [
  {title: '#', width: 50, dataIndex: 'index',align:"center",customRender:({text,record,index})=>index+1},
  {title: '培训项目代码', width: 80, dataIndex: 'xiangMuDaiMa',align:"center", ellipsis: true},
  {title: '培训项目名称', width: 280, dataIndex: 'xiangMuMing',align:"center", ellipsis: true},
  {title: '签发机关', width: 100, dataIndex: 'qianFaJiGuan',align:"center", ellipsis: true},
  {title: '签发日期', width: 140, dataIndex: 'qianFaRiQi',align:"center", ellipsis: true},
  {title: '有效期', width: 140, dataIndex: 'youXiaoQi',align:"center", ellipsis: true},
  {title: '证书状态', width: 80, dataIndex: 'zhuangTai',align:"center", ellipsis: true},
  {
    title: '操作',
    dataIndex: 'operation',
    width: 120,
    align: "center"
  },
];



/**
 * 查询列表数据
 */
const handleLoadData = async (chuanyuanId,chuanyuanName)=>{
  cid.value = chuanyuanId
  cname.value = chuanyuanName
  queryParams.chuanYuanId  = chuanyuanId
  tableLoading.value = true
  const resp = await useLoadChuanYuanKuPeiXunApi(queryParams)
  tableLoading.value = false
  tableDataAll.value = resp.data.records.map(c=>{
    c.edit = false
    c.youXiaoQiNum = 0
    return c
  })

  filterDataAll.value = resp.data.records.filter(c=>c.zhuangTai==1).map(c=>{
    c.edit = false
    c.youXiaoQiNum = 0
    return c
  })

  tableData.value = filterDataAll.value
  total.value = resp.data.total

  //查询船员项目证书下拉数据
  handleLoadChuaboZhengshuData()
}

//查询船员项目证书下拉数据
const handleLoadChuaboZhengshuData = async () => {
  var res = await useLoadChuanYuanZhengShuBiaoApi()
  chuanboZhengshuList.value = res.data
}


/**
 * 培训项目代码下拉框改变方法
 */
const handleSearchInfo = (record)=>{
  var item = chuanboZhengshuList.value.find(c=>c.xiangMuDaiMa==record.xiangMuDaiMa)
  record.xiangMuMing = item.xiangMuMing
  // record.qianFaJiGuan = item.qianFaJiGuan
  // record.qianFaRiQi = item.qianFaRiQi
  record.youXiaoQiNum = item.youXiaoQi
}

/**
 * 签发日期下拉框改变方法
 */
const handleChangeQianFa = (record)=>{
  var item = chuanboZhengshuList.value.find(c=>c.xiangMuDaiMa==record.xiangMuDaiMa)
  record.youXiaoQiNum = item.youXiaoQi

  var d = new Date(record.qianFaRiQi)
  d.setMonth(d.getMonth() + record.youXiaoQiNum * 1)
  if(record.youXiaoQiNum > 0) {
    record.youXiaoQi = d.Format("yyyy-MM-dd")
  }
}


// 删除
const handleDelete = async(id) => {
  await useDelChuanYuanKuPeiXunApi(id)
  useMessage().success("删除成功!");
  handleLoadData(cid.value, cname.value)
}

const handleDeleteItem = (index) => {
  tableData.value.splice(index,1)
}

const currentItem = ref({})
// 编辑
const handleEdit = (index) => {
  tableData.value[index].edit = true
  if(!tableData.value[index].qianFaRiQi) {
    const currentDate = new Date();
    const formattedTime = currentDate.toISOString().split('T')[0]
    // tableData.value[index].qianFaRiQi = formattedTime
  }
  currentItem.value = {...tableData.value[index]}
}
// 编辑取消
const handleEditDel = (index) => {
  tableData.value[index] = {...currentItem.value}
  tableData.value[index].edit = false
}

const handleEditSave = async (index) => {
  try {
    var items = tableData.value[index]
    if (!handleValidate(items)) {
      return
    }
    items.chuanYuanId = cid.value
    items.chuanYuanName = cname.value
    await useSaveUpdateChuanYuanKuPeiXunApi(items)
    useMessage().success("修改成功")
    tableData.value[index].edit = false
    currentItem.value = {}
  }catch (e) {
    useMessage().error(e.msg)
  }
}

const handleSave = async (index) => {
  try {
    var items = tableData.value[index]
    if (!handleValidate(items)) {
      return
    }
    items.id = ''
    items.chuanYuanId = cid.value
    items.chuanYuanName = cname.value
    const res = await useSaveUpdateChuanYuanKuPeiXunApi(items)
    useMessage().success("保存成功")
    tableData.value[index].id = res.data.id
    tableData.value[index].edit = false
    currentItem.value = {}
  }catch (e) {
    useMessage().error(e.msg)
  }
}

const handleValidate = (items) => {
  if(!items.xiangMuDaiMa){
    useMessage().error("请输入培训项目代码")
    return false;
  }
  return true;
}

const handleAdd = ()=>{
  addLoading.value = true
  const currentDate = new Date();
  const formattedTime = currentDate.toISOString().split('T')[0]
  tableData.value.unshift({zhuangTai:1})
  addLoading.value = false
}

const handleChangeBtn = ()=>{
  tableData.value = showChecked.value ? tableDataAll.value : filterDataAll.value
}

const handleClear = ()=>{
  tableData.value = []
  filterDataAll.value = []
  tableDataAll.value = []
}

defineExpose({
  handleLoadData,
  handleClear
})

</script>
